import { app, Menu } from 'electron'
import { dialog, ipcMain } from 'electron/main'
import windowUtil from './window-util'
import { is } from '@electron-toolkit/utils'
import { MenuItemConstructorOptions } from 'electron'

function genTemplate(): Array<MenuItemConstructorOptions> {
  const template = [
    {
      label: '文件',
      submenu: [
        {
          label: '打开zip压缩文件',
          async click(): Promise<void> {
            const { canceled, filePaths } = await dialog.showOpenDialog({
              filters: [
                {
                  extensions: ['zip'],
                  name: ''
                }
              ]
            })

            if (!canceled) {
              windowUtil.wins['main']?.webContents.send('open:file', filePaths[0])
            }
          }
        },
        {
          label: ' 退出 ',
          type: 'normal',
          click(): void {
            app.exit()
          }
        }
      ]
    }
  ]

  if (is.dev) {
    const devtools = {
      label: '打开devtools',
      type: 'normal',
      click(): void {
        windowUtil.wins['main'].webContents.openDevTools()
      }
    }
    template[0].submenu.splice(1, 0, devtools)
  }

  return template as Array<MenuItemConstructorOptions>
}

export function createMenu(): void {
  const menu = Menu.buildFromTemplate(genTemplate())

  Menu.setApplicationMenu(menu)
}
